<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use App\Http\Requests\Api\UserIntegralLogsRequest;
use App\Http\Resources\UserIntegralLogResource;
use App\Models\IntegralRule;
use App\Models\UserIntegralLog;

class UserIntegralLogsController extends Controller
{
    public function index(Request $request){
        $page_size = $request->page_size ? $request->page_size : 20;

        $logs = $request->user()->userIntegralLogs()
            ->where("is_checked",1)
            ->orderBy("id","desc")
            ->paginate($page_size);
        return UserIntegralLogResource::collection($logs);
    }

    public function store(UserIntegralLogsRequest $request,UserIntegralLog $userIntegralLog){
//            $data = $request->all();
        //非销售 权限检测
        $this->authorize("store",$userIntegralLog);

        $data = $request->all();
//        dd($data);
        $data['integral'] = ceil($data['price']/IntegralRule::getRatio());
        $data['recoder'] = $request->user()->nickname;
        $data['is_checked'] = false;
        $data['is_added'] = false;
        $userIntegralLog->fill($data);
        //积分变动和用户关联。
        $userIntegralLog->user()->associate($data['user_id']);
        $userIntegralLog->save();
        $status = [
            "msg"=>"设定完毕",
        ];
        return response()->json($status)->setStatusCode(200);
    }
}
